package sharetime.tag.service;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import sharetime.core.persistence.EntityExistsException;
import sharetime.core.service.BaseManager;
import sharetime.tag.domain.Tag;

@Service("tagManager")
@SuppressWarnings("unchecked")
public class DefaultTagManager extends BaseManager implements ITagManager {

	public List<Tag> getAllTags() {
		return dao.getAllInstances(Tag.class);
	}

	public List<String> getAllTagNames() {
		String[] params = {};
		Object[] values = {};

		return dao.getInstancesByNamedQueryAndNamedParam(String.class,
				"tag.findAllTagNames", params, values);
	}

	public void createTag(Tag tag) throws EntityExistsException {
		try {
			dao.create(tag);
		} catch (DataIntegrityViolationException e) {
			throw new EntityExistsException("Tag already exists");
		}
	}

	public void saveTag(Tag tag) {
		dao.save(tag);
	}

	public void updateTag(Tag tag) {
		dao.update(tag);
	}

	public Tag getTagByName(String name) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Tag.class);
		criteria.add(Restrictions.eq("name", name));
		List instancesByDetachedCriteria = dao.getInstancesByDetachedCriteria(criteria);
		if (instancesByDetachedCriteria.size() == 0) {
			return null;
		}
		return (Tag) instancesByDetachedCriteria.get(0);
	}
}
